package com.imooc.distributedemo.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.imooc.distributedemo.entity.Order;
import com.imooc.distributedemo.entity.OrderItem;
import com.imooc.distributedemo.entity.Product;
import com.imooc.distributedemo.entity.request.AddOrderReq;
import com.imooc.distributedemo.entity.request.CartProductVo;
import com.imooc.distributedemo.mapper.OrderItemMapper;
import com.imooc.distributedemo.mapper.OrderMapper;
import com.imooc.distributedemo.mapper.ProductMapper;
import com.imooc.distributedemo.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    private TransactionDefinition definition;

    private Lock lock = new ReentrantLock();


//    @Transactional
    @Override
    public synchronized  Long createOrder(AddOrderReq addOrderReq) throws Exception{

        TransactionStatus transaction = platformTransactionManager.getTransaction(definition);

        // 生成订单表
        //Snowflake snowflake = new Snowflake(1,1);
        long orderId = System.currentTimeMillis()+ RandomUtil.randomInt(4);//snowflake.nextId();
        Order order = Order.builder()
                .orderId(orderId)
                .orderStatus(1)
                .buyerAddress(addOrderReq.getBuyerAddress())
                .buyerName(addOrderReq.getBuyerName())
                .buyerPhone(addOrderReq.getBuyerPhone())
                .createTime(new Date())
                .updateTime(new Date())
                .build();
        orderMapper.insert(order);

        List<CartProductVo> cartProductVos = addOrderReq.getCartProductVos();
        for (CartProductVo vo:cartProductVos){
            // 添加订单明细
            OrderItem orderItem = OrderItem.builder()
                    .productId(vo.getProductId())
                    .count(vo.getCount())
                    .orderId(orderId)
                    .description("123")
                    .build();
            orderItemMapper.insert(orderItem);

            // 扣减库存
            /*Product product = productMapper.selectByPrimaryKey(vo.getProductId());
            if(product!=null){
                Integer leftAmount = product.getAmount()-vo.getCount();
                product.setAmount(leftAmount);
                productMapper.updateByPrimaryKeySelective(product);
            }*/
            Product product = productMapper.selectByPrimaryKey(vo.getProductId());
            if(product==null){
                platformTransactionManager.rollback(transaction);
                throw new Exception("购买商品:"+vo.getProductId()+"不存在");
            }
            log.warn(Thread.currentThread().getName()+"查询当前库存数为:"+product.getAmount());
            if(vo.getCount() > product.getAmount()){
                platformTransactionManager.rollback(transaction);
                throw new Exception("商品"+product.getProductName()+"仅剩下"+product.getAmount()+
                        "件，无法购买.");
            }
            productMapper.updateProductCount(vo.getCount(),vo.getProductId());
        }

        platformTransactionManager.commit(transaction);
        return orderId;
    }

    @Override
    public Long createOrderBlock(AddOrderReq addOrderReq) throws Exception {
        Product product = null;
        lock.lock();
            TransactionStatus transaction = platformTransactionManager.getTransaction(definition);

            // 生成订单表
            //Snowflake snowflake = new Snowflake(1,1);
            long orderId = System.currentTimeMillis()+ RandomUtil.randomInt(4);//snowflake.nextId();
            Order order = Order.builder()
                    .orderId(orderId)
                    .orderStatus(1)
                    .buyerAddress(addOrderReq.getBuyerAddress())
                    .buyerName(addOrderReq.getBuyerName())
                    .buyerPhone(addOrderReq.getBuyerPhone())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();
            orderMapper.insert(order);

            List<CartProductVo> cartProductVos = addOrderReq.getCartProductVos();
            for (CartProductVo vo:cartProductVos){
                // 添加订单明细
                OrderItem orderItem = OrderItem.builder()
                        .productId(vo.getProductId())
                        .count(vo.getCount())
                        .orderId(orderId)
                        .description("123")
                        .build();
                orderItemMapper.insert(orderItem);

                // 扣减库存
            /*Product product = productMapper.selectByPrimaryKey(vo.getProductId());
            if(product!=null){
                Integer leftAmount = product.getAmount()-vo.getCount();
                product.setAmount(leftAmount);
                productMapper.updateByPrimaryKeySelective(product);
            }*/
                product = productMapper.selectByPrimaryKey(vo.getProductId());
                if(product==null){
                    platformTransactionManager.rollback(transaction);
                    throw new Exception("购买商品:"+vo.getProductId()+"不存在");
                }
                log.warn(Thread.currentThread().getName()+"查询当前库存数为:"+product.getAmount());
                if(vo.getCount() > product.getAmount()){
                    platformTransactionManager.rollback(transaction);
                    throw new Exception("商品"+product.getProductName()+"仅剩下"+product.getAmount()+
                            "件，无法购买.");
                }
                productMapper.updateProductCount(vo.getCount(),vo.getProductId());
            }

            platformTransactionManager.commit(transaction);
            lock.unlock();
            return orderId;

    }

    @Override
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }
}
